package interviewusa;

import java.util.List;


public class Solution {

    public static void main(String[] args) {
        Solution m = new Solution();
        ListNode head = new ListNode(1);
        ListNode n1 = new ListNode( 2);
        head.next = n1;
        ListNode n2 = new ListNode( 3);
        n1.next = n2;
        ListNode n3 = new ListNode( 3);
        n2.next = n3;
        ListNode n4 = new ListNode( 4);
        n3.next = n4;
        ListNode n5 = new ListNode( 4);
        n4.next = n5;
        ListNode n6 = new ListNode( 5);
        n5.next = n6;
        head = m.removeElements(head);
        m.print(head);

    }
    public void print(ListNode head) {
        ListNode cur = head;
        while (cur != null) {
            System.out.println(cur.val);
            cur = cur.next;
        }
    }
    public ListNode removeElements(ListNode head) {

        ListNode curr = head;
        ListNode pre = new ListNode(-1);
        pre.next = head;
        while (curr.next != null) {
            if (curr.val == curr.next.val) {
                ListNode node = curr.next;
                while (node != null) {
                    if (curr.val == node.val) {
                        node = node.next;
                    } else {
                        break;
                    }
                }
                pre.next = node;
                if (head == curr) {
                    head = node;
                }
                curr = node;
            } else {
                pre = curr;
                curr = curr.next;
            }
        }
        return head;
    }
}
class ListNode {
    int val;
    ListNode next;

    public ListNode(int x) {
        this.val = x;
    }


}